<template>
  <div id="orderList" class="order-list-page">
    <!-- header -->
    <section class="header-section">
      <!-- header title -->
      <magic-header titleName="我的订单" :returnNative="$route.params.native"></magic-header>
      <!-- header 搜索框 查询全部订单时展示 -->
      <section class="search-section">
        <form class="search" onsubmit="return false">
          <input type="search" id="search" v-model="orderIdBySearch" placeholder="商品名, 订单号" autocomplete="off">
        </form>
      </section>
      <!-- header tab页 -->
      <section class="tab-section">
        <div>
          <mu-tabs :value="activeTab" @change="handleTabChange" class="test">
            <mu-tab value="0" title="全部" />
            <mu-tab value="1" title="待付款" />
            <mu-tab value="2" title="待使用" />
            <mu-tab value="3" title="待评价" />
            <mu-tab value="4" title="退货/退款" />
          </mu-tabs>
        </div>
      </section>
    </section>
    <!-- list -->
    <section class="list-section">
      <div v-if="!orders || orders.length === 0">
        <empty message="暂时没有订单"></empty>
      </div>
      <div v-else>
        <ma-scroll :getMore="loadBottom" :allLoaded="allLoaded" :down="true" :showMsg="true" :init="isInit">
          <!-- route link  :to="{name: ROUTE_NAME_ORDERDETAIL, params: {orderId: item.id}}"-->
          <div class="one-order" v-for="(item,index) in orders" :key="index">
            <!-- order item title -->
            <div class="order-item-title">
              <span>{{'订单号:' + item.sn}}</span>
              <!-- <span class="state">代发货</span> -->
            </div>
            <!-- order item info -->
            <panel class="order-item-info" v-for="(product,index) in item.orderItems" v-tap="{methods:go,params:{orderId: item.id}}" :key="index" :value="product" :orderType="item.orderType">
              <div slot="desc" class='desc'>
                {{product.desc}}
              </div>
              <price slot="price" class="order-item-price" v-if="item.couponDiscount > 0" :value="Number(item.amount) < 0 ? '0.00' : item.amount"></price>
              <price slot="price" class="order-item-price" v-if="item.couponDiscount == 0" :value="product.price"></price>
              <span slot="number" class="number">X{{product.quantity}}</span>
            </panel>
            <!-- order item button -->
            <div layout="column" class="order-item-buttons">
              <div layout="row" layout-align="flex-end center" class="order-item-price-count" flex>
                <span flex>
                  合计:
                  <span v-html="'¥'+(item.amount && (Number(item.amount) <= 0 ? '0.00' : item.amount) || '0.00')"></span>
                  共{{item.count || '0'}}件
                  <span>(含运费: ¥{{item.freight}})</span>
                </span>
              </div>
              <!--<mu-divider shallowInset/>-->
              <div class="order-item-button" flex>
                <order-button color="#8C8C8C" border="#8C8C8C" v-if="(item.type === '1'||item.type === '11')||((item.method === '1'||item.method === '2')&&item.type === '5')" v-tap="{methods: operate, item: item, operateType: 0}">
                  取消订单
                </order-button>
                <order-button color="#FBAD59" border="#FBAD59" v-if="[1,3,7,8,13].indexOf(Number(item.orderType)) == -1 && item.type === '1'&&item.method === '0'" v-tap="{methods: operate, item: item, operateType: 1}">
                  {{item.isSubscription !=='1'?'立即支付':Number(item.amountPaid) == '0'?'支付订金':'支付尾款'}}
                </order-button>
                <order-button color="#888888" border="#BEBEBE" v-if="[1,3,7,8,13].indexOf(Number(item.orderType)) == -1 && (item.type === '2' || item.type === '3' || item.type === '6')&&(item.method === '0'||item.method === '1')&&(item.orderType == 0)" v-tap="{methods: operate, item: item, operateType: 2}">
                  物流跟踪
                </order-button>
                <order-button color="#FBAD59" border="#FBAD59" v-if="item.type === '3'" v-tap="{methods: operate, item: item, operateType: 3}">
                  立即评价
                </order-button>
                <order-button color="#FBAD59" border="#FBAD59" v-if="item.isReviewed === '1'" v-tap="{methods: operate, item: item, operateType: 4}">
                  查看评价
                </order-button>
                <order-button color="#FBAD59" border="#FBAD59" v-if="[1,3,7,8,13].indexOf(Number(item.orderType)) == -1 && item.type === '2'" v-tap="{methods: operate, item: item, operateType: 5}">
                  确认收货
                </order-button>
                <order-button color="#FBAD59" border="#FBAD59" v-if="[1,3,7,8,13].indexOf(Number(item.orderType)) == -1 && item.type === '7' || item.type === '8' || item.type === '10' || item.type === '12'" v-tap="{methods: operate, item: item, operateType: 6}">
                  重新购买
                </order-button>
              </div>
            </div>
          </div>
        </ma-scroll>
      </div>
    </section>
    <!-- 各种弹出框 提示信息 输入密码等... -->
    <section class="tip-section">
      <!-- 取消订单 原因 -->
      <cancel-order :isShow="cancelOrderShow" @submitCancalOrder="cancelOrder"></cancel-order>
      <!-- 支付相关 -->
      <section>
        <!-- 输入密码 -->
        <model ref="passwordModel" title="请输入支付密码">
          <password v-model="password"></password>
        </model>
        <!-- 密码输入错误提示 -->
        <model modelType="prompt" title="" :isShow="passwordShow">
          <h4 slot>支付密码输入错误, 请重试</h4>
          <div slot="work" layout="row" layout-align="space-between center" flex>
            <a flex v-tap="{methods: payByBalance}">重试</a>
            <a flex v-tap="{methods: setPassword}">找回密码</a>
          </div>
        </model>
        <!-- 支付方式选择 -->
        <mu-bottom-sheet :open="paymentObj.paymentTypeShow" @close="closePaymentType">
          <mu-list @itemClick="closePaymentType">
            <mu-sub-header class="text-center">
              支付详情
            </mu-sub-header>
            <payment :value="orderItem" :selectedPaymentMethodId="orderItem.paymentMethodId" :orderId="orderItem.id" :callback="payment" v-if="orderItem" :sum="orderItem.orderItems[0].price" type="buy"></payment>
          </mu-list>
        </mu-bottom-sheet>
      </section>
      <!-- 确认收货 -->
      <model :isShow="confirmOrderShow" title=" " v-on:closeIsModel="confirmOrder">
        请确认是否已经收到货物
      </model>
    </section>
  </div>
</template>

<script>
// components
import magicHeader from "components/magicHeader";
import empty from "components/empty-page.vue";
import loadmore from "components/loadmore";
import panel from "components/panel";
import price from "components/price";
import orderButton from "components/order-button";
import cancelOrder from "components/cancelOrder";
import payment from "../payment/p_payment.vue";
import model from "components/model/model.vue";
import password from "components/password/password.vue";
// services
import {
  ListOrderEx,
  UpdateOrder,
  BalancePayment,
  AddCartItem
} from "services/orders/order";
// resource

export default {
  components: { magicHeader, empty, loadmore, panel, price, orderButton, cancelOrder, payment, model, password },
  data() {
    return {
      // env
      isWxPublic: false, // 判断当前环境
      // route
      activeTab: "0", // 当前激活的tab页, 查询订单list的请求参数 type
      ROUTE_NAME_ORDERLIST: "orderlist",
      ROUTE_NAME_ORDERDETAIL: "orderDetail",
      // view-model
      allLoaded: false, // 是否已读取全部数据
      orderIdBySearch: "", // 搜索的订单id
      page: {
        index: 0,
        count: 3
      },
      orders: [],
      orderItem: null, // 当前操作的订单项
      password: "",
      // condition
      confirmOrderShow: false, // 确认收货
      passwordShow: false, // 密码输入
      cancelOrderShow: false, // 取消订单原因选择框
      paymentObj: {
        // 支付相关参数
        paymentTypeShow: false
      },
      isInit: true
    };
  },
  computed: {
    // tabIndex() {
    //   return this.activeTab.match(/tab(\d)/)[1];
    // }
  },
  beforeRouteEnter(to, from, next) {
    next(vm => {
      vm.activeTab = String(to.params.status)
    })
  },
  created() {
    if (this.$.env === "wxPublic") {
      this.isWxPublic = true;
    }
    this.activeTab = String(this.$route.params.status)
    this.init();
  },
  mounted() {
    let el = document.querySelector('#search')
    el && el.addEventListener('keyup', (event) => {
      if (event.keyCode === 13) {
        document.getElementById('search').blur()
        this.activeTab = "0";
        this.pageInit();
        this.listOrderEx();
      }
    })
    // let status = this.$route.params.status && this.$route.params.status.toString() || '0'
    // getOrder(this, status)
  },
  methods: {
    // init method
    init() {
      this.listOrderEx();
    },
    go(params) {
      console.log(params.params)
      this.$router.push({
        name: this.ROUTE_NAME_ORDERDETAIL,
        params: params.params
      })
    },
    // 分页信息初始化
    pageInit() {
      this.page.index = 0;
      this.page.count = 3;
      this.orders = [];
    },
    // 瀑布流触发
    loadBottom() {
      return new Promise((resolve, reject) => {
        this.listOrderEx()
          .then(res => {
            resolve(res)
          })
      })
    },
    /**
     * 查询订单列表
     * type	类型 0：全部，1：待付款，2：执行，3：待评价，4：退货/款
     */
    listOrderEx() {
      let that = this
      return new Promise((resolve, reject) => {
        ListOrderEx.bind(that)(that.getListOrderExRequest(), resp => {
          that.page.index = that.page.index + that.page.count;
          console.log(resp);
          that.orders = that.orders.concat(...this.getProductInOrderItem(resp.orders));
          // this.orders =
          //   this.activeTab == 0 ? ordertest1.orders : ordertest2.orders;
          // 是否数据全部读取完
          if (resp.orders.length < that.page.count) {
            that.allLoaded = true;
          }
          resolve(that.orders)
        }, (err, code) => {
          this.$.toast(err);
        });
      })

    },
    // 获取请求
    getListOrderExRequest() {
      let request = {
        index: String(this.page.index),
        count: String(this.page.count),
        type: this.activeTab
      };

      if (this.orderIdBySearch) {
        request.searchValue = this.orderIdBySearch;
      }
      return request;
    },
    // 响应处理
    getProductInOrderItem(arr) {
      arr.forEach(order => {
        order.orderItems.forEach(orderItem => {
          orderItem.product = Object.assign({}, orderItem.product, {
            "image": orderItem.image,
            "name": orderItem.name,
            "fullName": orderItem.fullName
          })
        })
      })

      return arr
    },
    /**
     * 订单操作
     * @param orderItem 订单数据
     * @param operateType 操作类型
     * @description 0-取消订单 1-支付 2-物流跟踪 3-立即评价 4-查看评价 5-确认收货 6-重新购买
     */
    operate(params) {
      let orderItem = (this.orderItem = params.item);
      let operateType = params.operateType;
      switch (operateType) {
        case 0: // 取消订单
          this.showCancelOrderReason();
          break;
        case 1: // 支付 (立即支付 支付订金 支付尾款)
          this.showPaymentType();
          break;
        case 2: // 物流跟踪
          this.logistics(this.orderItem)
          break;
        case 3: // 立即评价
          this.evaluation(this.orderItem)
          break;
        case 4: // 查看评价
          this.evaluationView(this.orderItem)
          break;
        case 5: // 确认收货
          this.showConfirmOrder()
          break;
        case 6: // 重新购买
          this.purchaseAgain(this.orderItem)
          break;
        default:
          break;
      }
    },
    /* 取消订单methods: showCancelOrderReason closeCancelOrderReason cancelOrder*/
    // 选择取消原因
    showCancelOrderReason() {
      this.cancelOrderShow = true;
    },
    // 选择取消原因
    closeCancelOrderReason() {
      this.cancelOrderShow = false;
    },
    // 取消订单
    cancelOrder(content) {
      console.log(111)
      // service invoke
      if (content) {
        if (content == "default") {
          this.$.toast("请选择原因");
        } else {
          UpdateOrder.bind(this)({
            type: "0",
            orderId: this.orderItem.id,
            content: content
          }, resp => {
            this.pageInit();
            this.listOrderEx();
            this.closeCancelOrderReason();
          });
        }
      } else {
        this.closeCancelOrderReason();
      }
    },
    /* 支付methods: closePaymentType showPaymentType payment payByBalance balancePayment setPassword */
    // 关闭支付方式选择
    closePaymentType() {
      this.paymentObj.paymentTypeShow = false;
    },
    // 展示支付方式选择
    showPaymentType() {
      // 展示支付方式
      this.paymentObj.paymentTypeShow = true;
      // this.paymentObj.value = this.orderItem;
      // this.paymentObj.value.orderId = this.orderItem.id;
    },
    /**
     * 支付
     * @param payway 0-支付宝 2-余额
     */
    payment(params, payway) {
      // 余额支付, 展示密码输入框
      if (payway === "2") {
        this.closePaymentType();
        this.payByBalance();
      } else {
        this.$.push("router_pay", {
          orderId: this.orderItem.id,
          payType: payway
        }, res => {
          this.closePaymentType();
          if (res === "0") {
            this.$.toast("支付成功");
            this.pageInit();
            this.listOrderEx();
          }
          if (res === "1") {
            this.$.toast("支付失败");
          }
          if (res === "2") {
            this.$.toast("支付取消");
          }
        }
        );
      }
    },
    // 余额支付
    payByBalance() {
      let vm = this;
      this.passwordShow = false;
      let passwordModel = this.$refs.passwordModel;
      let _close = passwordModel.close;
      let _name = _close.name;
      // 注入model的close方法, 点击按钮会首先调用close方法
      if (_name !== "customClose") {
        passwordModel.close = function customClose() {
          let args = arguments;
          if (args && !args[0].confirm) {
            _close.bind(passwordModel)(...args);
            return;
          }
          if (vm.password.length < 6) {
            vm.$.toast("请输入合理密码");
            return;
          }
          _close.bind(passwordModel)({ confirm: true });
        };
      }
      // 绑定按钮方法
      passwordModel.show().then(() => {
        //  点击确定按钮
        if (vm.password.length < 6) {
          vm.$.toast("请输入合理密码");
        } else {
          this.balancePayment();
        }
      }, () => {
        vm.$.toast("支付取消");
      });
    },
    // 调用server 余额支付方法
    balancePayment() {
      BalancePayment.bind(this)({
        password: this.password,
        orderId: this.orderItem.id
      }, resp => {
        // order detail
        this.$router.push({
          name: this.ROUTE_NAME_ORDERDETAIL,
          params: {
            orderId: this.orderItem.id
          }
        });
      }, (err, code) => {
        if (code === "376") {
          // 会员卡余额不足
          this.$.toast("余额不足");
        } else if (code === "378") {
          // 支付密码未设定, 跳到设置密码页面
          this.$.toast("支付密码未设定");
          this.setPassword();
        } else if (code === "380") {
          // 支付密码错误, 弹出框, 可以重置密码
          this.passwordShow = true;
        } else {
          this.$.toast(err);
        }
      });
    },
    // 跳到设置支付密码页面
    setPassword() {
      this.$.push("router_setPayPassword", null, () => {
        console.log("页面成功跳转");
      });
    },
    /* 物流跟踪methods: logistics */
    // 物流跟踪
    logistics(orderItem) {
      console.log(orderItem);
      this.$router.push({
        name: 'l_logistics',
        params: {
          shippingSn: orderItem.shippings[0].sn
        }
      })
    },
    /* 评价methods: evaluation evaluationView */
    // 评价
    evaluation(orderItem) {
      this.$router.push({
        name: 'el_selfEvaluation',
        query: {
          orderItem: JSON.stringify(orderItem)
        }
      })
    },
    // 查看评价
    evaluationView(orderItem) {
      this.$router.push({
        name: 'el_selfEvaluation_view',
        query: {
          orderItem: JSON.stringify(orderItem)
        }
      })
    },
    /* 确认收货methods: showConfirmOrder closeConfirmOrder confirmOrder */
    showConfirmOrder() {
      this.confirmOrderShow = true;
    },
    closeConfirmOrder() {
      this.confirmOrderShow = false;
    },
    // 确认收货
    confirmOrder(params) {
      if (params === 'true') {
        UpdateOrder.bind(this)({
          type: "1",
          orderId: this.orderItem.id
        }, resp => {
          // 跳转到订单详情
          this.$router.push({
            name: this.ROUTE_NAME_ORDERDETAIL,
            params: {
              orderId: this.orderItem.id
            }
          })
        }, (err, code) => {
          this.$.toast(err)
          // 确认收货出错, 可能为订单过期, 重新查询订单列表
          this.pageInit();
          this.listOrderEx();
        });
      }
      this.closeConfirmOrder()
    },
    /* 重新购买methods: purchaseAgain */
    purchaseAgain(orderItem) {
      // invoke service
      let reqArr = this.getPurchaseAgainRequests(orderItem);
      reqArr && AddCartItem.bind(this)(reqArr, resp => {
        this.$router.push({
          name: 'asc_shoppingCart'
        })
      })
    },
    // 获取重新购买 请求
    getPurchaseAgainRequests(orderItem) {
      let requests = []
      orderItem.orderItems && orderItem.orderItems.forEach(item => {
        // categoryType 0:整车;1:车品；2:服务
        if (item.product.categoryType === '0') {
          // 整车 跳转订单支付
          item.product.quantity = '1'
          this.$router.push({
            name: 'o_orderConfirm',
            query: {
              cartItems: JSON.stringify(item.product)
            }
          })
          return false;
        } else {
          requests.push({
            productId: item.product.id,
            quantity: '1'
          })
        }
      })

      return requests
    },
    // tab 页切换
    handleTabChange(tab) {
      this.activeTab = tab;
      this.pageInit();
      this.allLoaded = false;
      this.orderIdBySearch = "";
      // tab toggle
      this.$router.replace({
        name: this.ROUTE_NAME_ORDERLIST,
        params: {
          status: this.activeTab
        }
      });

      this.init();
    }
  }
};
</script>
<style lang="scss" scoped>
@mixin lineHeight($value: 30px) {
  height: $value;
  line-height: $value;
}
.order-list-page {
  height: 100%;
  display: flex;
  flex-direction: column;
  .header-section {
    position: fixed;
    z-index: 100;
    width: 100%;
    background-color: #fff;
    .search-section {
      .search {
        width: 100%;
        padding: 6px 10px;
        background-color: #c9c9ce;
        z-index: 100;
        input {
          width: 100%;
          @include lineHeight(30px);
          display: block;
          outline: none;
          border: none;
          border-radius: 10px;
          background: url(../../assets/search.svg) no-repeat 15px;
          background-color: #fff;
          text-align: center;
        }
      }
    }
    .tab-section {
      div {
        width: 100%;
        z-index: 101;
        // &.active {
        //   top: 91px;
        // }
      }
    }
  }
  .list-section {
    height: calc(100% - 130px);
    position: relative;
    flex-grow: 1;
    margin-top: 130px;
    .order-item-title {
      padding: 10px 15px;
      display:flex;
      justify-content:space-between;
      position: relative;
      &:after {
        content: " ";
        position: absolute;
        left: 0;
        bottom: 0;
        width: 100%;
        height: 0;
        border-bottom: solid #d7d7d7 1px;
        transform: scaleY(0.2);
      }
      span {
        color: #898989;
        font-size: 12px;
      }
      .state{
        color: #f98700;
      }
    }
    .order-item-info {
      .number {
        text-align: right;
        margin-right: 15px;
        color: #b4b4b4;
        font-size: 1.1rem;
      }
    }

    .order-item-buttons {
      text-align: right;
      .order-item-price-count {
        font-size: 1rem;
        color: #898989;
        padding: 10px;
      }
      .order-item-button {
        padding-right: 10px;
        .order-button {
          margin-right: 5px;
          padding: 2px 12px;
        }
      }
    }
    #wrapper {
      top: 10px;
    }
  }
  .test {
    margin-bottom: 0;
  }
}
</style>
<style lang="scss">
.order-list-page {
  .scroller {
    margin: 0;
    width: 100%;
  }
}
</style>

